<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="50%"
    :before-close="handleClose"
  >
    <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-10个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-10个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model.trim="formData.manager" filterable placeholder="请选择" style="width:80%" @focus="getUser()">
          <el-option
            v-for="item in people"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </el-form-item>
    </el-form>
    <!-- <span slot="footer" class="dialog-footer" /> -->
  </el-dialog>
</template>

<script>
import { getDepartmentList, addDepartment, getDepartmentDetail, updateDepartment } from '@/api/departments'
import { getUsersimple } from '@/api/employees'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    treeNode: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    // 部门名称函数校验规则
    const vilitaderName = async(rules, value, callback) => {
      const { depts } = await getDepartmentList() // 获取最新的部门信息
      let arr = []
      if (this.formData.id) {
        // 有id，编辑部门校验
        // 筛选出所有兄弟部门（自己不能等于自己且pid都相同）
        arr = depts.filter(item => {
          return item.id !== this.treeNode.id && item.pid === this.treeNode.pid
        })
      } else {
        // 无id,新增部门校验
        // 筛选出部门底下有子部门（item的pid === 传过来的数据的id【筛选出传过来的数据的子id】）
        arr = depts.filter(item => item.pid === this.treeNode.id)
      }
      const isRepat = arr.some(item => item.name === value) // 判断筛选出来的数组是否与用户输入的名字相同
      isRepat ? callback(new Error(`${value}已经存在，请重新创建`)) : callback()
    }
    // 部门编码函数校验规则
    const vilitaderCode = async(rules, value, callback) => {
      const { depts } = await getDepartmentList()
      let isRepeat = false
      if (this.treeNode.id) {
        isRepeat = depts.some(item => item.code === value && item.id !== this.treeNode.id) // 部门编码是唯一的，判断所有部门编码是否和value一致，如果一致，返回true
      } else {
        isRepeat = depts.some(item => item.code === value) // 部门编码是唯一的，判断所有部门编码是否和value一致，如果一致，返回true
      }
      isRepeat ? callback(new Error(`部门编码${value}已经存在`)) : callback()
    }
    return {
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-10个字符', trigger: 'blur' },
          { validator: vilitaderName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-10个字符', trigger: 'blur' },
          { validator: vilitaderCode, trigger: 'blur' }
        ],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-300个字符' }
        ]
      },
      people: [] // 员工简单列表
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    handleClose() {
      this.$refs.form.resetFields()
      this.$emit('update:visible', false)
    },
    async getUser() {
      this.people = await getUsersimple()
    },
    // form提交表单事件
    async submit() {
      await this.$refs.form.validate()
      // 判断有无id，有id是编辑部门，没有就是添加id
      if (this.formData.id) {
        // 编辑部门
        await updateDepartment(this.formData)
        this.$message.success('编辑部门成功')
      } else {
        // 新增部门
        await addDepartment({ ...this.formData, pid: this.treeNode.id })
        this.$message.success('添加部门成功')
      }
      this.handleClose()
      this.$emit('addDept')
    },
    // 通过id获取部门详情
    async getDepartmentDetail(id) {
      const res = await getDepartmentDetail(id)
      this.formData = res
    }
  }
}
</script>

<style>

</style>
